#df
import socket,os,urllib,time,sys,base64,getpass

def execmd(data):
	print 'Execute command :  ',data
	receivedCmd = data.split()
	i = receivedCmd[0].rfind('/')
	cmddir = receivedCmd[0][:i]
	try:
		os.chdir(cmddir) 
	except OSError:
		print 'Cannot change working directory'

	try:
		if len(receivedCmd) == 1: os.spawnl(os.P_NOWAIT,receivedCmd[0],receivedCmd[0])
		if len(receivedCmd) == 2: os.spawnl(os.P_NOWAIT,receivedCmd[0],receivedCmd[0],receivedCmd[1])
		if len(receivedCmd) == 3: os.spawnl(os.P_NOWAIT,receivedCmd[0],receivedCmd[0],receivedCmd[1],receivedCmd[2])
		if len(receivedCmd) == 4: os.spawnl(os.P_NOWAIT,receivedCmd[0],receivedCmd[0],receivedCmd[1],receivedCmd[2],receivedCmd[3])
		if len(receivedCmd) == 5: os.spawnl(os.P_NOWAIT,receivedCmd[0],receivedCmd[0],receivedCmd[1],receivedCmd[2],receivedCmd[4],receivedCmd[5])
	except :
		print 'Cannot execute Command'


def geturl (data):
	#time.clock
	print 'get file from http server:'
	filelink = data.split()[0]
	filename = data.split()[1]
	def reporthook(*a): 
		time.clock()
		percent = (a[0]*a[1])*100/a[2]
		if percent <= 100: 
			#print 'file total size is %s K,now %s %s has been transfered,speed: %s K/S' % ((a[2])/1024,percent,'%',int(a[1]/1024/time.clock()))
			print 'file total size is %s K,now %s %s has been transfered' % ((a[2])/1024,percent,'%')
		#print a
	print filelink, "---------->", filename
	try:
		urllib.urlretrieve(filelink, filename, reporthook)
	except IOError:
		print 'unable to connect to http server'
	print 'file transfered completed '
	print 'file %s has been saved to %s' % (filelink,filename)


def ver(now_ver):
	start_run_time = time.ctime(time.time())
	return """
______________________________________________________________________________
		          [Spilot Commander Server]
		   Copyright by Spilot 2003-2004  Ver %s 
		   Server Start At : %s
______________________________________________________________________________
	""" % (now_ver,start_run_time)


def main ():
	print ver(1.0)
	port = 27377
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	# Accept UDP datagrams, on the given port, from any sender
	s.bind(("", port))
	print "server listening:"
	while 1:
	 # Receive up to 1,024 bytes in a datagram
		print 'ready now :'
		data, addr = s.recvfrom(1024)
		data = base64.decodestring(data)
		if data[0] == ':':
			try:
				execmd(data[1:])
			except:
				print 'execute command error'
				continue
		if data[0] == ';':
			try:
				geturl(data[1:])
			except:
				print 'get file from http server error'
				continue
		print ' '


if __name__ == '__main__':
	main()
